﻿using DevExpress.ExpressApp.DC;
using DevExpress.Persistent.Base;
using System.ComponentModel;
using System.Xml.Linq;

namespace EasyXaf.LowCode.WorkflowEditors.Models.Activities;

[DomainComponent]
[ImageName("WF_Container")]
[XafDisplayName("容器(Container)")]
[ActivityOrder(70)]
[ActivityGroup(ActivityGroupConsts.CommonGroupName)]
public class ContainerActivity : Activity, IContainerActivity
{
    public override string ImageName => "WF_Container";

    [Browsable(false)]
    public ObjectCollection<IActivity> Activities { get; }

    ObjectCollection<IActivity> ISequence.Activities => Activities;

    public ContainerActivity(IWorkflow workflow, ISequence sequence)
        : base(workflow, sequence)
    {
        Caption = "容器";
        Activities = new ObjectCollection<IActivity>(this);
    }

    public ISequence FindSequence(string sequenceId)
    {
        return Workflow.FindSequence(sequenceId, this);
    }

    public IActivity FindActivity(string activityId)
    {
        return Workflow.FindActivity(activityId, this);
    }

    public INode FindNode(string nodeId)
    {
        return Workflow.FindNode(nodeId, this);
    }

    public override void OnCreated()
    {
        base.OnCreated();

        Activities.Add(new StartActivity(Workflow, this).Created());
        Activities.Add(new EndActivity(Workflow, this).Created());
    }

    public override void OnCloned()
    {
        base.OnCloned();

        foreach (var activity in Activities)
        {
            activity.OnCloned();
        }
    }

    public override void WriteToXml(XElement element)
    {
        base.WriteToXml(element);

        if (Activities.Any())
        {
            var activitiesElement = new XElement("Activities");
            element.Add(activitiesElement);
            foreach (var activity in Activities)
            {
                var activityElement = new XElement(activity.GetType().Name);
                activity.WriteToXml(activityElement);
                activitiesElement.Add(activityElement);
            }
        }
    }

    public override void ReadFromXml(XElement element)
    {
        base.ReadFromXml(element);

        if (element.Element("Activities") is XElement activitiesElement)
        {
            foreach (var activityElement in activitiesElement.Elements())
            {
                Activities.Add(Workflow.CreateActivityFromXml(activityElement, this));
            }
        }
    }
}
